using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;

namespace MvcEngine.Mvc.UI
{
    public class GridFooter<T> : IGridFooter<T> where T : class
    {
        private List<Func<GridRowViewData<T>, IDictionary<string, object>>> attributes = new List<Func<GridRowViewData<T>, IDictionary<string, object>>>();
        private readonly string value;
        private bool htmlEncoded;

        /// <summary>
        /// Creates a new instance of the GridColumn class
        /// </summary>
        public GridFooter(string value)
        {
            this.value = value;
        }

        IGridFooter<T> IGridFooter<T>.Attributes(Func<GridRowViewData<T>, IDictionary<string, object>> attributes)
        {
            this.attributes.Add(attributes);
            return this;
        }

        IGridFooter<T> IGridFooter<T>.DoNotEncode()
        {
            this.htmlEncoded = false;
            return this;
        }

        public Func<GridRowViewData<T>, IDictionary<string, object>> Attributes
        {
            get { return GetAttributesFromRow; }
        }

        private IDictionary<string, object> GetAttributesFromRow(GridRowViewData<T> row)
        {
            var dictionary = new Dictionary<string, object>();
            var pairs = attributes.SelectMany(attributeFunc => attributeFunc(row));

            foreach (var pair in pairs)
            {
                dictionary[pair.Key] = pair.Value;
            }

            return dictionary;
        }

        public object GetValue()
        {
            if(htmlEncoded)
                return HttpUtility.HtmlEncode(value);
            return value;
        }
    }
}